package cn.hdustea.shopNavigation.ui.view.main

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.KeyEvent
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import cn.hdustea.shopNavigation.R
import cn.hdustea.shopNavigation.config.ConfigKey
import cn.hdustea.shopNavigation.ui.view.AccountActivity
import cn.hdustea.shopNavigation.ui.view.bottom.AttentionFragment
import cn.hdustea.shopNavigation.ui.view.bottom.HomeFragment
import cn.hdustea.shopNavigation.ui.view.bottom.NavigationFragment
import cn.hdustea.shopNavigation.ui.view.bottom.mine.MineFragment
import com.hdustea.base.util.ToastUtil
import kotlinx.android.synthetic.main.activity_home.*
import java.util.*


class HomeActivity : AppCompatActivity() {
    private var mFragments = arrayListOf<Fragment>()
    private var mCurPosition = -1
    private var currentClickTime: Long = 0
    private var isPermissionRequested = false

    companion object {
        fun startActivity(context: Context, position: Int? = 0) {
            val intent = Intent(context, HomeActivity::class.java)
            intent.putExtra("position", position)
            context.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_home)
        permissionGet()
        initView()
    }

    private fun initView() {
        initFragment()
        navigation.inflateMenu(R.menu.menu_home)
        navigation.setOnNavigationItemSelectedListener { menuItem ->
            when (menuItem.itemId) {
                R.id.home -> {
                    switchFragment(0)
                }
                R.id.market -> {
                    switchFragment(1)
                }
                R.id.attention -> {
                    switchFragment(2)
                }
                R.id.mine -> {
                    switchFragment(3)
                }
            }
            true
        }
        val menuItemMine = navigation.menu.getItem(3)
        menuItemMine.setOnMenuItemClickListener {
            if (ConfigKey.isLogin()) {
                false
            } else {
                AccountActivity.startActivity(this)
                true
            }
        }
    }

    private fun initFragment() {
        mFragments.add(HomeFragment.getInstance())
        mFragments.add(NavigationFragment.getInstance())
        mFragments.add(AttentionFragment.getInstance())
        mFragments.add(MineFragment.getInstance())
        val transaction = supportFragmentManager.beginTransaction()
        for (fragment in supportFragmentManager.fragments) {
            transaction.remove(fragment)
        }
        for (fragment in mFragments) {
            transaction.add(R.id.container, fragment)
            transaction.hide(fragment)
        }
        transaction.show(mFragments[0])
        transaction.commit()
    }

    private fun switchFragment(position: Int) {
        if (mCurPosition == position) return
        if (mFragments.size <= position) return
        synchronized(this) {
            val transaction = supportFragmentManager.beginTransaction()
            for (fragment in mFragments) {
                transaction.hide(fragment)
            }
            transaction.show(mFragments[position])
            transaction.commit()
            mCurPosition = position
        }

    }

    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        val appName = resources.getString(R.string.app_name)
        if (event?.keyCode == KeyEvent.KEYCODE_BACK) {
            if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
                if (currentClickTime <= 0) {
                    ToastUtil.showShort("再按一次退出$appName")
                    currentClickTime = System.currentTimeMillis()
                } else {
                    val currentTimeMillis = System.currentTimeMillis()
                    if (currentTimeMillis - currentClickTime > 2000) {
                        ToastUtil.showShort("再按一次退出$appName")
                        currentClickTime = currentTimeMillis
                    } else {
                        ConfigKey.setCityMarketsSelect("")
                        finish()
                    }
                }
            }
            return true
        }
        return super.dispatchKeyEvent(event)
    }

    private fun permissionGet() {
        if (Build.VERSION.SDK_INT >= 23 && !isPermissionRequested) {
            isPermissionRequested = true
//            if (!Settings.System.canWrite(this)) {
//                val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS)
//                intent.data = Uri.parse("package:$packageName")
//                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//                startActivity(intent)
//            }
            val permissionsList = ArrayList<String>()
            val permissions = arrayOf(
                    Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.ACCESS_NETWORK_STATE,
                    Manifest.permission.INTERNET,
                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.MODIFY_AUDIO_SETTINGS,
                    Manifest.permission.ACCESS_WIFI_STATE,
                    Manifest.permission.CHANGE_WIFI_STATE,
                    Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
                    Manifest.permission.CAMERA
            )
            for (perm in permissions) {
                if (PackageManager.PERMISSION_GRANTED != checkSelfPermission(perm)) {
                    permissionsList.add(perm)
                    // 进入到这里代表没有权限.
                }
            }
            if (permissionsList.isEmpty()) {
                return
            } else {
                requestPermissions(permissionsList.toTypedArray(), 0)
            }
        }
    }
}